/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.pay.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.shiro.realms.Ta;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.entity.taccount.Taccount;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.base.service.taccount.TaccountService;
import com.jeesite.modules.custom.service.CodeRuleService;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.pay.entity.TpaymentDetail;
import com.jeesite.modules.payment.entity.Tap;
import com.jeesite.modules.payment.entity.TapDetail;
import com.jeesite.modules.payment.service.TapService;
import com.jeesite.modules.prepay.entity.Tprepayment;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.prepay.service.TprepaymentService;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.poi.ss.formula.functions.T;
import com.jeesite.modules.pay.entity.Tpay;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.pay.entity.Tpayment;
import com.jeesite.modules.pay.service.TpaymentService;

import java.util.List;
import java.util.Map;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 付款单Controller
 * @author wsm
 * @version 2021-03-16
 */
@Controller
@RequestMapping(value = "${adminPath}/pay/tpayment")
public class TpaymentController extends BaseController {

	@Autowired
	private TpaymentService tpaymentService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private ServiceOrderService serviceOrderService;
	@Autowired
	private TapService tapService;
	@Autowired
	private CodeRuleService codeRuleService;
	@Autowired
	private TprepaymentService tprepaymentService;
	@Autowired
	private TaccountService taccountService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Tpayment get(String paymentId, boolean isNewRecord) {
		return tpaymentService.get(paymentId, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("pay:tpayment:view")
	@RequestMapping(value = {"list", ""})
	public String list(Tpayment tpayment, Model model) {
		model.addAttribute("tpayment", tpayment);

		//供应商
		List<Supplier> supplierList = supplierService.findList(new Supplier());
		model.addAttribute("supplierList",supplierList);
		//服务订单
		List<ServiceOrder> serviceOrderList = serviceOrderService.findList(new ServiceOrder());
		model.addAttribute("serviceOrderList",serviceOrderList);
		return "modules/pay/tpaymentList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("pay:tpayment:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<Tpayment> listData(Tpayment tpayment, HttpServletRequest request, HttpServletResponse response) {
		tpayment.setPage(new Page<>(request, response));
		Page<Tpayment> page = tpaymentService.findPage(tpayment);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("pay:tpayment:view")
	@RequestMapping(value = "form")
	public String form(Tpayment tpayment, Model model,String apId) {

			Tap tap =new Tap();
			tap.setApId(apId);
			tap=tapService.get(tap);

			tpayment.setSupplierId(tap.getSupplierId());
			tpayment.setDate(new Date());
			tpayment.setSupplier(tap.getSupplier());
			tpayment.setServiceOrderId(tap.getServiceOrderId());
			//tpayment.setApCode(tap.getApCode());
			tpayment.setCurrency(tap.getCurrency());
			//循环添加详情
			TpaymentDetail tpaymentDetail =null;
			List<TpaymentDetail> tpaymentDetailList =new ArrayList<>();

			for (TapDetail tapDetail : tap.getTapDetailList()) {

				tpaymentDetail =new TpaymentDetail();
				tpaymentDetail.setBrand(tapDetail.getBrand());
				tpaymentDetail.setArea(tapDetail.getArea());
				tpaymentDetail.setModel(tapDetail.getModel());
				tpaymentDetail.setCarId(tapDetail.getCarId());
				tpaymentDetail.setFrameNumber(tapDetail.getFrameNumber());
				tpaymentDetail.setExpenseItem(tapDetail.getExpenseItem());
				tpaymentDetail.setActualApAmount(tapDetail.getActualApAmount());
				tpaymentDetail.setApAmount(tapDetail.getApAmount());
				tpaymentDetail.setApCode(tap.getApCode());
				tpaymentDetail.setRowNumber(tapDetail.getRowNumber());
				tpaymentDetail.setActualApAmount(null);
				if(tapDetail.getActualApAmount()==null){
					tpaymentDetail.setPayentLeft(tapDetail.getApAmount()-0);
				}else{
					tpaymentDetail.setPayentLeft(tapDetail.getApAmount()-tapDetail.getActualApAmount());
				}

				tpaymentDetailList.add(tpaymentDetail);
			}
			tpayment.setTpaymentDetailList(tpaymentDetailList);
			//银行
		    Taccount taccount =new Taccount();
		    taccount.setIsBank("1");
		    List<Taccount> taccountList = taccountService.findList(taccount);
		    model.addAttribute("taccountList",taccountList);
		    //供应商
			List<Supplier> supplierList = new ArrayList<>();
			supplierList.add(tpayment.getSupplier());
			model.addAttribute("supplierList",supplierList);
			//服务订单
			List<ServiceOrder> serviceOrderList = new ArrayList<>();

			ServiceOrder serviceOrder = new ServiceOrder();
			serviceOrder.setServiceOrderId(tpayment.getServiceOrderId());
			serviceOrder =serviceOrderService.get(serviceOrder);
			serviceOrderList.add(serviceOrder);
			model.addAttribute("serviceOrderList",serviceOrderList);
			//应付单
			List<Tap> tapList =new ArrayList<>();
			tapList.add(tap);
			model.addAttribute("tapList",tapList);

		model.addAttribute("tpayment", tpayment);

		return "modules/pay/tpaymentForm";
	}

	/**
	 * 查看表单详情
	 */
	@RequiresPermissions("pay:tpayment:view")
	@RequestMapping(value = "detail")
	public String detail(Tpayment tpayment, Model model) {

		model.addAttribute("tpayment", tpayment);
		//银行
		Taccount taccount=tpayment.getTaccount();
		List<Taccount> taccountList = new ArrayList<>();
		taccountList.add(taccount);
		model.addAttribute("taccountList",taccountList);
		//供应商
		List<Supplier> supplierList = new ArrayList<>();
		supplierList.add(tpayment.getSupplier());
		model.addAttribute("supplierList",supplierList);
		//服务订单
		List<ServiceOrder> serviceOrderList = new ArrayList<>();

		ServiceOrder serviceOrder = new ServiceOrder();
		serviceOrder.setServiceOrderId(tpayment.getServiceOrderId());
		serviceOrder =serviceOrderService.get(serviceOrder);
		serviceOrderList.add(serviceOrder);
		model.addAttribute("serviceOrderList",serviceOrderList);
		//应付单
		/*List<Tap> tapList =new ArrayList<>();
		Tap tap =new Tap();
		tap.setApCode(tpayment.getApCode1());
		tap =tapService.get(tap);
		tapList.add(tap);
		model.addAttribute("tapList",tapList);*/
		return "modules/pay/tpaymentDetail";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("pay:tpayment:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Tpayment tpayment) {

		if(tpayment.getIsNewRecord()){
			tpayment.setPaymentCode(codeRuleService.getCode("customsdeclaration001"));
			tpayment.setCreateBy(UserUtils.getUser().getLoginCode());
			tpayment.setStatus1("1");
		}

		Tprepayment tprepayment =null;
		//设置付款单应付余额
		for(int i=0;i<tpayment.getTpaymentDetailList().size();i++){
			if(tpayment.getTpaymentDetailList().get(i).getActualApAmount()!=null&&!"".equals(tpayment.getTpaymentDetailList().get(i).getActualApAmount())){

			tpayment.getTpaymentDetailList().get(i).setPayentLeft(tpayment.getTpaymentDetailList().get(i).getApAmount()-tpayment.getTpaymentDetailList().get(i).getActualApAmount());
			tpayment.getTpaymentDetailList().get(i).setPrepaymentCode(tpayment.getTpaymentDetailList().get(i).getPrepaymentCode1());
			//判断有无核销
			if(tpayment.getTpaymentDetailList().get(i).getPrepaymentCode()!=null&&!"".equals(tpayment.getTpaymentDetailList().get(i).getPrepaymentCode())){
				tprepayment =new Tprepayment();
				tprepayment.setPrepaymentCode(tpayment.getTpaymentDetailList().get(i).getPrepaymentCode());
				tprepayment=tprepaymentService.findList(tprepayment).get(0);
				tprepayment =tprepaymentService.get(tprepayment);

				//修改预付款的金额
				for (TprepaymentEstimated tprepaymentEstimated : tprepayment.getTprepaymentEstimatedList()) {
					if(tprepaymentEstimated.getRowNumber().equals(tpayment.getTpaymentDetailList().get(i).getRowNumber())&&tprepaymentEstimated.getPrepaymentType().equals(tpayment.getTpaymentDetailList().get(i).getExpenseItem())){
						//已核销金额设置
						if(tprepaymentEstimated.getPaymentAmountActual()==null){
							tprepaymentEstimated.setPaymentAmountActual(tpayment.getTpaymentDetailList().get(i).getActualApAmount());
						}else {
							tprepaymentEstimated.setPaymentAmountActual(tprepaymentEstimated.getPaymentAmountActual()+tpayment.getTpaymentDetailList().get(i).getActualApAmount());
						}
						//未核销金额设置
						tprepaymentEstimated.setPaymentAmountEstimated(tprepaymentEstimated.getPaymentSumActual()-tprepaymentEstimated.getPaymentAmountActual());

						//预付单设置金额
						tprepayment.setPrepaymentBalance(tprepayment.getPrepaymentBalance()-tpayment.getTpaymentDetailList().get(i).getActualApAmount());
					}
				}
                //查看预付款单还有多少未报销金额,修改状态
				if(tprepayment.getPrepaymentBalance()==0){
					tprepayment.setStatus1("4");
				}else{
					tprepayment.setStatus1("3");
				}
				tprepaymentService.save(tprepayment);
			}

		}
		}
		Tap tap =null;
		//修改应付单
		for(int i=0;i<tpayment.getTpaymentDetailList().size();i++){
			TpaymentDetail  tpaymentDetail=tpayment.getTpaymentDetailList().get(i);

			tap = new Tap();
		    tap.setApCode(tpaymentDetail.getApCode());
		    tap =tapService.findList(tap).get(0);
		    tap =tapService.get(tap);

		    //设置一个布尔值判定应付单状态
		    boolean b =true;
		    //找到应付单下的对应应付详情
			for (TapDetail tapDetail : tap.getTapDetailList()) {
				//判断下面每个应付与实付对比
				if(tapDetail.getActualApAmount()!=tapDetail.getApAmount()){
					b=false;
				}
				if(tpayment.getTpaymentDetailList().get(i).getActualApAmount()!=null&&!"".equals(tpayment.getTpaymentDetailList().get(i).getActualApAmount())){

					if(tapDetail.getRowNumber().equals(tpaymentDetail.getRowNumber())){
						//设置回显实付
						if(tapDetail.getActualApAmount()==null){
							tapDetail.setActualApAmount(tpaymentDetail.getActualApAmount());
						}else{
							tapDetail.setActualApAmount(tapDetail.getActualApAmount()+tpaymentDetail.getActualApAmount());
						}
						//设置应付余额
						tapDetail.setPayLeft(tapDetail.getApAmount()-tapDetail.getActualApAmount());
					}
				}
			}
			if(b==true){
				tap.setStatus1("4");
			}else {
				tap.setStatus1("3");
			}
			tapService.save(tap);
		}

		tpaymentService.save(tpayment);
		if (tpayment.getIsNewRecord()){
			codeRuleService.updateCurrentNumber("customsdeclaration001");
		}

		return renderResult(Global.TRUE, text("保存付款单成功！"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("pay:tpayment:delete")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Tpayment tpayment) {
		tpaymentService.delete(tpayment);
		return renderResult(Global.TRUE, text("删除付款单成功！"));
	}

	/**
	 * 付款选择页面-代付款列表
	 * @param tpayment
	 * @return
	 */
	@RequestMapping(value = "getPaidInfo")
	@ResponseBody
	public List<Tpay> getPaidInfo(Tpayment tpayment){
		List<Tpay> paidInfo = tpaymentService.getPaidInfo(tpayment);
		return paidInfo;
	}

	/**
	 * 查询付款选择列表
	 * @param tpay
	 * @param model
	 * @return
	 */
	@RequiresPermissions("pay:tpayment:view")
	@RequestMapping(value = {"paidList", ""})
	public String getPaidList(Tpay tpay,Model model){
		//供应商
		List<Supplier> supplierList = supplierService.findList(new Supplier());
		model.addAttribute("supplierList",supplierList);
		//银行
		Taccount taccount =new Taccount();
		taccount.setIsBank("1");
		List<Taccount> taccountList = taccountService.findList(taccount);
		model.addAttribute("taccountList",taccountList);
		//服务订单
		List<ServiceOrder> serviceOrderList = serviceOrderService.findList(new ServiceOrder());
		model.addAttribute("serviceOrderList",serviceOrderList);
		//应付单
		List<Tap> tapList = tapService.findList(new Tap());
		model.addAttribute("tapList",tapList);

		model.addAttribute("tpay",tpay);
		return "modules/pay/tpaymentSelect";
	}
}